package com.sgcc.pda.bluetooth.ui;

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.data.BleDevice;
import com.sgcc.pda.bluetooth.api.IBlueConnStatusListener;
import com.sgcc.pda.bluetooth.blueinterface.ConnectBlueCallBack;
import com.sgcc.pda.bluetooth.blueinterface.IBleConnectListener;
import com.sgcc.pda.bluetooth.blueinterface.IOnFoundDeviceListener;
import com.sgcc.pda.bluetooth.blueinterface.IOnReConnectListener;
import com.sgcc.pda.bluetooth.bluetoothmanager.BleBluetoothManager;
import com.sgcc.pda.bluetooth.bluetoothmanager.BlueManager;
import com.sgcc.pda.bluetooth.bluetoothmanager.ClassicBluetoothManager;
import com.sgcc.pda.bluetooth.config.Constant;
import com.sgcc.pda.bluetooth.utils.BlueDeviceInfoUtil;
import com.sgcc.pda.bluetooth.utils.ToolGson;
import com.sgcc.pda.mdrh.task.lib_tools_bluetool.R;

/**
 * 描 述：蓝牙列表界面
 * 作 者：yangzhi
 * 时 间：2020/3/6 10:49
 * 版 本：1.0
 * 版 权： Copyright (c) remarkables-united.Co.Ltd. All rights reserved.
 */
public class BluetoothListActivity extends Activity {

    private static final String TAG = "BlueManager";
    //适配器
    private DeviceAdapter mDeviceAdapter;
    //蓝牙是否打开
    private boolean isOpen = false;
    //蓝牙类型
    private int blueType = Constant.BLUE_CLS;
    //开关
    private ImageView ivSwitch;
    //动画
    private ImageView ivAnim;
    //列表
    private ListView lv;
    //空白布局
    private View viewEmpty;
    //关闭
    private ImageView ivClose;
    //设备布局
    private RelativeLayout rlDevice;
    //扫描
    private TextView tvScan;

    public static void setBlueConnStatusListener(IBlueConnStatusListener blueConnStatusListener) {
        BluetoothListActivity.blueConnStatusListener = blueConnStatusListener;
    }

    private static IBlueConnStatusListener blueConnStatusListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth_list);
        initView();
        initData();
        initListener();
    }

    /**
     * 初始化
     */
    private void initView() {
        //开关
        ivSwitch = findViewById(R.id.iv_switch);
        //动画
        ivAnim = findViewById(R.id.iv_anim);
        ivAnim.setImageResource(R.drawable.pro_anim);
        //关闭
        ivClose = findViewById(R.id.iv_close);
        //空白布局
        viewEmpty = findViewById(R.id.view_empty);
        //列表
        lv = findViewById(R.id.lv_item);
        //扫描
        tvScan = findViewById(R.id.tv_scan);
        //设备布局
        rlDevice = findViewById(R.id.rl_device);
        Window window = getWindow();
        WindowManager wm = getWindowManager();
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);

        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = (int) (wm.getDefaultDisplay().getWidth() * 0.8);
        int maxHeight = (int) (wm.getDefaultDisplay().getWidth() * 0.7);
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT >= maxHeight ? maxHeight : ViewGroup.LayoutParams.WRAP_CONTENT;
//        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 这里还可以设置lp.x，lp.y在x轴，y轴上的坐标，只是这个位置是基于Gravity的
        window.setAttributes(lp);
        lv.setDividerHeight(0);
    }


    /**
     * 监听事件
     */
    private void initListener() {
        tvScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scan();
            }
        });
        //连接蓝牙
        ivSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //扫描蓝牙设备还是断开连接
                if (isOpen) {
                    BlueManager.getInstance(BluetoothListActivity.this).clearConnectedThread();
                    changeView(false);
                    BlueManager.getInstance(BluetoothListActivity.this).cancelScan();
                } else {
                    changeView(true);
                    scan();
                }
            }
        });

        /*
         * 列表点击 连接或绑定
         */
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (Constant.BLUE_BLE == blueType) {
                    //ble蓝牙
                    final BleDevice bleDevice = (BleDevice) lv.getItemAtPosition(position);
                    if (null != bleDevice) {
                        bleConn(bleDevice);
                    }
                } else if (Constant.BLUE_CLS == blueType) {
                    //经典蓝牙
                    final BluetoothDevice bluetoothDevice = (BluetoothDevice) lv.getItemAtPosition(position);
                    if (null != bluetoothDevice) {
                        ClassicBluetoothManager.getInstance(BluetoothListActivity.this).clearTimer();
                        conn(bluetoothDevice);
                    }
                }
            }
        });

        /*
         * 自动重连监听,连接成功关闭界面
         */
        BlueManager.getInstance(BluetoothListActivity.this).setAutoConnListener(new IOnReConnectListener() {
            @Override
            public void onStartConn() {

            }

            @Override
            public void onConnSuccess() {
                Toast.makeText(BluetoothListActivity.this, "自动重连成功", Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void onConnFailure() {

            }
        });

        //关闭
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BlueManager.getInstance(BluetoothListActivity.this).cancelScan();
                finish();
            }
        });
    }


    /**
     * 初始化蓝牙
     */
    private void initData() {
        BlueManager.getInstance(this).configBlue(this.getApplication(), BlueManager.getInstance(this).getBlueType(), BlueManager.getInstance(this).isAutoReConn(), BlueManager.getInstance(this).getmReConnCount());
        mDeviceAdapter = new DeviceAdapter(BluetoothListActivity.this);
        mDeviceAdapter.setBlueType(blueType);
        lv.setAdapter(mDeviceAdapter);
        if (isBlueEnable()) {
            changeView(true);
        } else {
            changeView(false);
        }
        //扫描蓝牙
        scan();
    }

    /**
     * 判断蓝牙是否可用
     */
    private boolean isBlueEnable() {
        return BlueManager.getInstance(BluetoothListActivity.this).isBlueEnable();
    }

    /**
     * 扫描蓝牙
     */
    private void scan() {
        if (Constant.BLUE_BLE == blueType) {
            //ble蓝牙
            BleBluetoothManager.getInstance(BluetoothListActivity.this).scanDevice(new IOnFoundDeviceListener() {
                @Override
                public void bluetoothScanStart() {
                    changeView(true);
                    //开始扫描
                    Log.e(TAG, "ble 开始扫描");
                    ivAnim.setVisibility(View.VISIBLE);
                    showAnim();
                    mDeviceAdapter.clearBleScanDevice();

                    /*
                     * 先判断上次连接的蓝牙是否连接，已连接的话添加在第一个
                     */
                    BleDevice lastDevice = BlueDeviceInfoUtil.getInstance().getBleDevice();
                    if (null != lastDevice && BleBluetoothManager.getInstance(BluetoothListActivity.this).isConn(lastDevice)) {
                        mDeviceAdapter.addLastBleDevice(lastDevice);
                        Log.e(TAG, "添加上次连接的蓝牙：NAME:" + lastDevice.getName() + "MAC:" + lastDevice.getMac());
                    }
                    mDeviceAdapter.notifyDataSetChanged();
                    rlDevice.setVisibility(View.VISIBLE);
                }

                @Override
                public void clsFoundDevice(BluetoothDevice bondDevice) {
                    //使用经典蓝牙搜索到的设备
                    Log.e(TAG, "经典蓝牙扫描到：NAME:" + bondDevice.getName());
                }

                @Override
                public void bleFoundDevice(BleDevice bleDevice) {
                    if (!TextUtils.isEmpty(bleDevice.getName())) {
                        //使用ble搜索到的设备
                        mDeviceAdapter.addBleDevice(bleDevice);
                        Log.e(TAG, "扫描到：NAME:" + bleDevice.getName() + "MAC:" + bleDevice.getMac());
                    }
                }

                @Override
                public void bluetoothScanFinsh() {
                    //扫描结束关闭动画
                    ivAnim.setVisibility(View.GONE);
                    mDeviceAdapter.notifyDataSetChanged();
                    Log.e(TAG, "ble蓝牙 扫描结束");
                }
            });

        } else if (Constant.BLUE_CLS == blueType) {
            //经典蓝牙
            ClassicBluetoothManager.getInstance(this).setActiveDisConnected(false);
            mDeviceAdapter.clearClsScanDevice();

            /*
             * 先判断上次连接的蓝牙是否连接，已连接的话添加在第一个
             */
            BluetoothDevice lastDevice = BlueDeviceInfoUtil.getInstance().getClsDevice();
            if (null != lastDevice && ClassicBluetoothManager.getInstance(BluetoothListActivity.this).isConnectBlue(lastDevice)) {
                mDeviceAdapter.addClsDevice(lastDevice);
                Log.e(TAG, "添加上次连接的蓝牙：NAME:" + lastDevice.getName() + "MAC:" + lastDevice.getAddress());
            }
            ClassicBluetoothManager.getInstance(this).scanDevice(new IOnFoundDeviceListener() {
                @Override
                public void bluetoothScanStart() {
                    changeView(true);
                    //开始扫描
                    rlDevice.setVisibility(View.VISIBLE);
                    ivAnim.setVisibility(View.VISIBLE);
                    showAnim();
                    Log.e(TAG, "经典蓝牙 开始扫描");
                    mDeviceAdapter.notifyDataSetChanged();
                }

                @Override
                public void clsFoundDevice(BluetoothDevice bluetoothDevice) {
                    if (!TextUtils.isEmpty(bluetoothDevice.getName())) {
                        //使用经典蓝牙搜索到的设备
                        mDeviceAdapter.addClsDevice(bluetoothDevice);
                        Log.e(TAG, "扫描到：NAME:" + bluetoothDevice.getName() + "MAC:" + bluetoothDevice.getAddress());
                    }
                }

                @Override
                public void bleFoundDevice(BleDevice bleDevice) {
                    //使用ble搜索到的设备
                    Log.e(TAG, "bleDevice扫描到：NAME:" + bleDevice.getName());
                }

                @Override
                public void bluetoothScanFinsh() {
                    //扫描结束
                    //扫描结束关闭动画
                    ivAnim.setVisibility(View.GONE);
                    mDeviceAdapter.notifyDataSetChanged();
                    Log.e(TAG, "经典蓝牙 扫描结束");
                }

            });
        }

    }

    /**
     * 连接ble蓝牙
     *
     * @param bleDevice ble蓝牙
     */
    private void bleConn(final BleDevice bleDevice) {
        if (BleBluetoothManager.getInstance(BluetoothListActivity.this).isConn(bleDevice)) {
            Toast.makeText(BluetoothListActivity.this, "蓝牙已连接", Toast.LENGTH_SHORT).show();
            if (null != mDeviceAdapter) {
                mDeviceAdapter.notifyDataSetChanged();
            }
        } else {
            BleBluetoothManager.getInstance(BluetoothListActivity.this).startConn(bleDevice, new IBleConnectListener() {
                @Override
                public void onStartConn() {
                    //开始进行连接
                    Log.e(TAG, "ble 开始连接");
                    showProgressDialog("蓝牙连接中...");
                }

                @Override
                public void onConnSuccess() {
                    //连接成功并发现服务
                    Log.e(TAG, bleDevice.getKey() + "连接成功");
                    Toast.makeText(BluetoothListActivity.this, "蓝牙连接成功", Toast.LENGTH_SHORT).show();
                    if (null != mDeviceAdapter) {
                        mDeviceAdapter.notifyDataSetChanged();
                    }
                    hideProgressDialog();
                    if (null != blueConnStatusListener) {
                        blueConnStatusListener.connected();
                    }
                    BluetoothListActivity.this.finish();
                }

                @Override
                public void onConnFailure(String error) {
                    //连接不成功
                    Log.e(TAG, bleDevice.getName() + "连接失败");
                    Toast.makeText(BluetoothListActivity.this, "蓝牙连接失败", Toast.LENGTH_SHORT).show();
                    hideProgressDialog();
                    if (null != mDeviceAdapter) {
                        mDeviceAdapter.notifyDataSetChanged();
                    }
                }
            });
        }
    }


    /**
     * 连接经典蓝牙
     *
     * @param bluetoothDevice 经典蓝牙
     */
    private void conn(final BluetoothDevice bluetoothDevice) {
        if (null != bluetoothDevice && ClassicBluetoothManager.getInstance(BluetoothListActivity.this).isConnectBlue(bluetoothDevice)) {
            Toast.makeText(BluetoothListActivity.this, "蓝牙已连接", Toast.LENGTH_SHORT).show();
            if (null != mDeviceAdapter) {
                mDeviceAdapter.notifyDataSetChanged();
            }
            return;
        }
        ClassicBluetoothManager.getInstance(BluetoothListActivity.this).connect(bluetoothDevice, new ConnectBlueCallBack() {
            @Override
            public void onStartConnect() {
                Log.e(TAG, "开始连接");
                showProgressDialog("蓝牙连接中...");
            }

            @Override
            public void onConnectSuccess(BluetoothDevice bluetoothDevice) {
                Log.e(TAG, "连接成功 bluetoothDevice" + bluetoothDevice.getAddress());
                hideProgressDialog();
                if (null != bluetoothDevice) {
                    Log.e(TAG, "连接成功1，保存对象" + bluetoothDevice.getAddress());
                    BlueDeviceInfoUtil.getInstance().setDeviceInfo(Constant.BLUE_CLS, ToolGson.getJsonStr(bluetoothDevice), Constant.CONNECTED);
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (null != mDeviceAdapter) {
                            mDeviceAdapter.notifyDataSetChanged();
                        }
                    }
                });
                if (null != blueConnStatusListener) {
                    blueConnStatusListener.connected();
                }
                BluetoothListActivity.this.finish();
            }

            @Override
            public void onConnectFail() {
                Log.e(TAG, "连接失败");
                hideProgressDialog();
                if (null != blueConnStatusListener) {
                    blueConnStatusListener.disConnected();
                }
                BlueDeviceInfoUtil.getInstance().setDeviceInfo(Constant.BLUE_CLS, ToolGson.getJsonStr(bluetoothDevice), Constant.DISCONNECTED);
            }
        });

    }

    private LoadingDialog loadingDialog;

    /**
     * 展示等待框
     *
     * @param msg 等待框提示文字
     */
    private void showProgressDialog(String msg) {
        loadingDialog = new LoadingDialog.Builder(this).setMsg(msg).creat();
        loadingDialog.show();
    }

    /**
     * 等待框消失
     */
    private void hideProgressDialog() {
        if (null != loadingDialog) {
            loadingDialog.dismiss();
        }
    }

    /**
     * 展示搜索动画
     */
    private void showAnim() {
        AnimationDrawable adProgressSpinner = (AnimationDrawable) ivAnim.getDrawable();
        if (adProgressSpinner != null && !adProgressSpinner.isRunning()) {
            adProgressSpinner.start();
            Log.e(TAG, "开始动画");
        }
    }

    /**
     * 改变界面
     *
     * @param open 蓝牙是否打开
     */
    private void changeView(boolean open) {
        if (open) {
            ivSwitch.setBackgroundResource(R.drawable.blue_open);
            rlDevice.setVisibility(View.VISIBLE);
            tvScan.setVisibility(View.VISIBLE);
            lv.setVisibility(View.VISIBLE);
            viewEmpty.setVisibility(View.GONE);
            isOpen = true;
        } else {
            ivSwitch.setBackgroundResource(R.drawable.blue_close);
            rlDevice.setVisibility(View.GONE);
            tvScan.setVisibility(View.GONE);
            ivAnim.setVisibility(View.GONE);
            viewEmpty.setVisibility(View.VISIBLE);
            lv.setVisibility(View.GONE);
            isOpen = false;
        }
    }

}
